package Demo1_15;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User：Lenovo
 * Date:2025-01-15
 * Time:23:40
 */
// 定义链表节点类
class ListNode {
    int val;
    ListNode next;
    ListNode(int x) {
        val = x;
        next = null;
    }
}

public class IntersectionOfTwoLinkedLists {
    public static ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if (headA == null || headB == null) {
            return null;
        }
        ListNode pointerA = headA;
        ListNode pointerB = headB;
        // 分别用两个指针遍历两个链表
        while (pointerA!= pointerB) {
            pointerA = pointerA == null? headB : pointerA.next;
            pointerB = pointerB == null? headA : pointerB.next;
        }
        return pointerA;
    }

    public static void main(String[] args) {
        // 创建第一个链表
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;

        // 创建第二个链表
        ListNode node6 = new ListNode(6);
        ListNode node7 = new ListNode(7);
        node6.next = node7;
        // 让第二个链表和第一个链表相交于 node3
        node7.next = node3;

        ListNode intersection = getIntersectionNode(node1, node6);
        if (intersection!= null) {
            System.out.println("Intersection node value: " + intersection.val);
        } else {
            System.out.println("No intersection found.");
        }
    }
}
